<!-- 角色管理  -->
<template>
  <div id="box">
    <el-row style="margin-top: 5px;">
      <el-col :span="1" :offset="22">
        <el-button
          size="small"
          type="primary"
          @click="centerDialogVisibleBase = true;"
        >
          新增角色
        </el-button>
      </el-col>
    </el-row>
    <div style="width: 100%;background-color: white;padding: 10px 20px;">
      <el-table
        border
        height="650px"
        highlight-current-row
        :data="tableData.filter(data => (!search.name|| data.name.toLowerCase().includes(search.name.toLowerCase())) && (!search.hospital || data.hospitalId.toLowerCase().includes(search.hospital.toLowerCase())) ).slice((currentPage-1)*pagesize,currentPage*pagesize)"
      >
        <el-table-column align="center" type="index" />
        <el-table-column align="center" label="角色编号" prop="code" />
        <el-table-column align="center" label="角色名称" prop="name" />
        <el-table-column align="center" label="创建人" prop="userName" />
        <el-table-column align="center" label="修改时间" prop="updateTime" />
        <el-table-column align="center" label="使用人数" prop="userCount" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button v-if="!(scope.row.name == '上报管理员' || scope.row.name == '审核管理员' || scope.row.name == '医院管理员')" type="text" @click="details(scope.row, scope.$index)">
              编辑角色
            </el-button>
            <el-button type="text" style="color: red;margin-left: 20px;" @click="deletes(scope.row)">
              查看人员
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 40]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--添加新角色-->
    <el-dialog
      title="添加新角色"
      :visible.sync="centerDialogVisibleBase"
      width="60%"
      center
      top="10vh"
      style="text-align: center;"
      :before-close="closeaddbase"
    >
      <el-form
        ref="addbase"
        :model="send"
        :rules="addbaserules"
        label-width="150px"
        label-position="top"
        style="width: 100%;border-bottom: 1px solid #F0F0EE;border-top: 1px solid #F0F0EE;padding: 10px 0;"
      >
        <!-- <el-form-item label="code" prop="code">
          <el-input v-model="send.code" style="width: 60%;" />
        </el-form-item> -->
        <el-form-item label="角色名称" prop="name">
          <el-select v-model="send.name" style="width: 25%;" placeholder="请选择角色名">
            <el-option v-for="(item, index) in sendOptions" :key="index" :label="item.label" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 100%;" label="移动端模块 :" prop="Appmodular">
          <el-checkbox-group v-model="send.Appmodular" style="display: flex;flex-wrap:wrap;">
            <el-checkbox v-for="(item,index) in Appmodular" :key="index" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item style="width: 100%;" label="网页端模块 :" prop="Webmodular">
          <el-checkbox-group v-model="send.Webmodular" style="display: flex;flex-wrap:wrap;">
            <el-checkbox v-for="(item,index) in webAll" :key="index" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- <el-form-item label="医院编码" prop="hospitalId">
          <el-input v-model="send.hospitalId" style="width:80%;" />
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="resetForm('addbase')">重置</el-button>
        <el-button size="medium" @click="handleClose('addbase')">取 消</el-button>
        <el-button size="medium" type="primary" @click="add(send,'addbase')">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改基本代码类别对话框-->
    <el-dialog
      v-if="centerDialogVisibleupdateBase"
      title="修改角色信息"
      :visible.sync="centerDialogVisibleupdateBase"
      width="60%"
      center
      style="text-align: center;"
      top="10vh"
      :before-close="closeupdatebase"
    >
      <el-form
        ref="updatebase"
        :model="getbase"
        :rules="updatebaserules"
        label-width="150px"
        label-position="top"
        style="width: 100%;border-bottom: 1px solid #F0F0EE;border-top: 1px solid #F0F0EE;padding: 10px 0;"
      >
        <!-- <el-form-item label="code" prop="code">
          <el-input disabled v-model="getbase.code" style="width: 60%;" />
        </el-form-item> -->
        <el-form-item label="角色名称" prop="name">
          <el-select v-model="getbase.name" style="width: 25%;" filterable disabled allow-create default-first-option placeholder="请选择角色名">
            <el-option v-for="(item, index) in sendOptions" :key="index" :label="item.label" :value="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 100%;" label="移动端模块 :" prop="modular">
          <el-checkbox-group v-model="getbase.modular" style="display: flex;flex-wrap:wrap;">
            <el-checkbox v-for="item in Appmodular" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item style="width: 100%;" label="网页端模块 :" prop="modular">
          <el-checkbox-group v-model="getbase.modular" style="display: flex;flex-wrap:wrap;">
            <el-checkbox v-for="(item,index) in webAll" :key="index" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="handleClose('updatebase')">取 消</el-button>
        <el-button size="medium	" type="primary" @click="updatebase(getbase,'updatebase')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看人员 -->
    <el-dialog
      v-if="viewPeople"
      title="查看人员信息"
      :visible.sync="viewPeople"
      width="60%"
      center
      style="text-align: center;"
      :before-close="closeviewPeople"
    >
      <el-table
        border
        height="350px"
        :data="viewList"
      >
        <el-table-column type="index" align="center" />
        <el-table-column label="用户工号" prop="jobNumber" />
        <el-table-column label="用户姓名" prop="nickname" />
        <el-table-column label="联系方式" prop="phoneNum" />
        <el-table-column label="用户职称" prop="userType" />
        <el-table-column label="所属科室" prop="departmentName" />
        <el-table-column label="账号权限" prop="authority" />
        <el-table-column label="分配角色" prop="userRole" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium	" type="primary" @click="viewPeople = false">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { findRolesByUserAllNew, saveRolesNew, updateRolesNew, queryMenusAll, setMenuToRole, queryFindById } from '@/api/back-management/BG_role'
export default {
  name: 'Role',
  props: {
    hospitalId: {
      type: [String, Number],
      default: '37'
    },
    regionId: {
      type: [String, Number],
      default: '0'
    }
  },
  data() {
    return {
      centerDialogVisibleBase: false, // 添加
      centerDialogVisibleupdateBase: false, // 修改
      viewPeople: false, // 查看
      tableData: [], // 回显表格
      Appmodular: [], // 移动
      webAll: [], // web
      search: {
        hospital: '',
        name: ''
      },
      /* 修改 */
      getbase: {
        name: '',
        modular: []
      },
      updatebaserules: {
        code: [{
          required: true,
          message: '请输入角色编码',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }],
        hospitalId: [{
          required: true,
          message: '请输入医院编码',
          trigger: 'blur'
        }],
        modular: [{
          required: true,
          message: '请选择移动-胸痛模块',
          trigger: 'blur'
        }]
      },
      /* 新增 */
      send: {
        name: '',
        Appmodular: [],
        Webmodular: []
        // hospitalId: ''
      },
      sendOptions: [{
        label: '全模块-测试',
        value: 0
      }, {
        label: '护士筛查',
        value: 1
      }, {
        label: '基层医院',
        value: 2
      }, {
        label: '救护车',
        value: 3
      }, {
        label: '分诊台',
        value: 4
      }, {
        label: '急诊抢救室/急诊门诊',
        value: 5
      }, {
        label: '心内科',
        value: 6
      }, {
        label: '神内科',
        value: 7
      }, {
        label: '心电图室',
        value: 8
      }, {
        label: '急诊科',
        value: 9
      }, {
        label: '心外科',
        value: 10
      }, {
        label: 'CT室',
        value: 11
      }, {
        label: '超声室',
        value: 12
      }, {
        label: '导管室/手术室',
        value: 13
      }, {
        label: '病例管理员',
        value: 14
      }, {
        label: '神外科',
        value: 15
      }, {
        label: '创伤骨科',
        value: 16
      }],
      addbaserules: {
        code: [{
          required: true,
          message: '请输入角色编码',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }],
        hospitalId: [{
          required: true,
          message: '请输入医院编码',
          trigger: 'blur'
        }],
        Appmodular: [{
          required: true,
          message: '请选择移动-胸痛模块',
          trigger: 'blur'
        }],
        Webmodular: [{
          required: true,
          message: '请选择web模块',
          trigger: 'blur'
        }]
      },
      /* 查看 */
      viewList: [],
      currentPage: 1, // 初始页
      pagesize: 10 //    每页的数据
    }
  },

  created() {
    this.getroles()
  },

  methods: {
    // 获取角色信息
    getroles() {
      this.mobileStroke = []
      this.mobileChestPain = []
      this.webAll = []
      const that = this
      var b = {
        token: this.$store.getters.token,
        hospitalId: this.hospitalId
      }
      findRolesByUserAllNew(b).then((res) => {
        const arr = []
        for (const index in res) {
          if (Array.isArray(res[index])) {
            arr.push(...res[index])
          }
        }
        that.tableData = arr
      })
      const c = {
        token: this.$store.getters.token
      }
      queryMenusAll(c).then(res => {
        const Allmodule = []
        res.forEach(item => {
          if (item.type === 1) {
            this.webAll.push(item)
          }
          if (item.type === 2) {
            Allmodule.push(item)
          }
          // if (item.module && item.module.indexOf(2) > -1) {
          //   Allmodule.push(item)
          // }
          // if (item.module && item.module.indexOf(3) > -1) {
          //   Allmodule.push(item)
          // }
          // if (item.module && item.module.indexOf(4) > -1) {
          //   this.webAll.push(item)
          // }
        })
        this.Appmodular = Array.from(new Set(Allmodule))
      })
    },
    // 分页尺寸改变
    handleSizeChange(size) {
      this.pagesize = size
    },
    // 分页换页
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
    },

    // 添加角色
    add(send, formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          // let code = this.regionId + this.hospitalId + send.code
          const menu = [...send.Appmodular, ...send.Webmodular]
          let menuIdConcatStr = ''
          menuIdConcatStr = Array.from(new Set(menu)).join(',')
          var b = {
            'regionId': send.name.value,
            // this.regionId,
            'menuIds': menuIdConcatStr,
            'name': send.name.label,
            'hospitalId': this.hospitalId,
            'token': this.$store.getters.token,
            'userId': this.$store.getters.userId
          }
          saveRolesNew(b).then(res => {
            if (res.toString().indexOf('云服务接口错误') > -1) {
              if (res.indexOf('用户没有权限添加当前医院角色') > -1) {
                this.$message({
                  message: '用户没有权限添加当前医院角色！',
                  type: 'error'
                })
              } else {
                this.$message({
                  message: '添加失败！',
                  type: 'error'
                })
              }
              this.centerDialogVisibleBase = false
              this.send = {
                // code: '',
                name: '',
                Appmodular: [],
                Webmodular: []
                // hospitalId: ''
              }
              this.getroles()
            } else {
              this.centerDialogVisibleBase = false
              this.send = {
                // code: '',
                name: '',
                Appmodular: [],
                Webmodular: []
                // hospitalId: ''
              }
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.getroles()
            }
          })
        } else {
          return false
        }
      })
    },
    handleClose(formName) {
      this.centerDialogVisibleupdateBase = false
      this.centerDialogVisibleBase = false
      this.resetForm(formName)
    },
    closeaddbase() {
      this.$nextTick(() => {
        this.handleClose('addbase')
      })
      this.resetForm('addbase')
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    // 修改角色
    details(data, index) {
      this.getbase.name = data.name
      this.getbase.id = data.id
      this.getbase.userName = data.userName
      this.getbase.hospitalId = data.hospitalId
      this.centerDialogVisibleupdateBase = true
      var b = {
        'roleId': data.id,
        'token': this.$store.getters.token
      }
      queryFindById(b).then(res => {
        if (res.indexOf('云服务接口错误') > -1) {
          this.$message.error('获取角色已有模块失败！')
        } else {
          this.getbase.modular = res
        }
      })
    },
    updatebase(getbase, formname) {
      console.log(this.getbase.name, 'formname')
      this.$refs[formname].validate((valid) => {
        if (valid) {
          const that = this
          let menuIdConcatStr = ''
          menuIdConcatStr = Array.from(new Set(getbase.modular)).join(',')
          const getBaseObj = this.sendOptions.filter(item => {
            return item.label === getbase.name
          })
          console.log(getBaseObj, 'getBaseObj')
          if (getBaseObj && getBaseObj.length > 0) {
            const a = {
              regionId: getBaseObj[0].value,
              menuIds: menuIdConcatStr,
              name: getBaseObj[0].label,
              id: getbase.id,
              userName: getbase.userName,
              hospitalId: getbase.hospitalId,
              token: this.$store.getters.token
            }
            updateRolesNew(a).then(res => {
              if (res.id) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                that.centerDialogVisibleupdateBase = false
                that.getroles()
                that.getbase = {
                  name: '',
                  modular: []
                }
              } else {
                this.$message({
                  message: '用户没有权限修改当前医院角色！',
                  type: 'error'
                })
                that.centerDialogVisibleupdateBase = false
                that.getroles()
                that.getbase = {
                  name: '',
                  modular: []
                }
              }
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          return false
        }
      })
    },
    closeupdatebase() {
      this.$nextTick(() => {
        this.handleClose('updatebase')
      })
      this.getroles()
    },
    // 查看人员
    deletes(data) {
      this.viewList = data.userList
      this.viewPeople = true
    },
    closeviewPeople(done) {
      done()
      this.getroles()
    }
  }
}
</script>

<style scoped>
  #box {
    background-color: white;
    width: 100%;
    height: 100%;
  }
  .el-checkbox-group{
    margin-left: 20px;
  }
  .el-checkbox{
    width: 148px;
  }
</style>
